package org.csu.jpetstore.web.servlet;

import org.csu.jpetstore.domain.Account;
import org.csu.jpetstore.service.AccountService;
import org.csu.jpetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

public class SignonServlet extends HttpServlet {

    private static final String SIGNON_FORM = "/WEB-INF/jsp/account/SignonForm.jsp";
    private static final String MAIN_FORM = "/WEB-INF/jsp/catalog/Main.jsp";

    private LogService logService;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(SIGNON_FORM).forward(req, resp);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        logService = new LogService();

        HttpSession session = request.getSession();

        AccountService accountService = new AccountService();

        Account loginAccount = accountService.login(username, password);

        String value1=request.getParameter("vCode");
        String value2=(String)session.getAttribute("checkcode");
        Boolean isSame = false;
        /*对比两个值（字母不区分大小写）*/
        if(value2.equalsIgnoreCase(value1)){
            isSame = true;
        }

        if(isSame) {
            if (loginAccount == null) {
                request.setAttribute("msg", "用户名或密码错误");
                request.getRequestDispatcher(SIGNON_FORM).forward(request, response);
            } else {
                HttpSession sessions = request.getSession();
                sessions.setAttribute("loginAccount", loginAccount);
                request.getRequestDispatcher(MAIN_FORM).forward(request, response);
            }
        }else {
            request.setAttribute("msg", "验证码错误");
            request.getRequestDispatcher(SIGNON_FORM).forward(request, response);
        }

        Account user = (Account) session.getAttribute("loginAccount");
        Date date = new Date();
        logService.insert(user.getUsername(), date.toString(), "登录");

    }

}
